<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>await的应用</title>
</head>
<body>
<script type="text/javascript">
    function sendAjax(url, data) {
        return new Promise((resolve, reject) => {
            // 实例 xhr
            const xhr = new XMLHttpRequest()
            // 绑定监听
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response)
                    else reject('请求出了点问题')
                }
            }
            // 整理参数
            let str = ''
            for (let key in data) {
                str += `${key}=${data[key]}`
            }
            str = str.slice(0, -1)
            xhr.open('GET', url + '?' + str)
            xhr.responseType = 'json'
            xhr.send()
        })
    }

    ;(async () => {
        try {
            // 第一次发送请求
            const res1 = await sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
            console.log('第1次请求成功了', res1)
            // 第二次发送请求
            const res2 = await sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
            console.log('第2次请求成功了', res2)
            // 第三次发送请求
            const res3 = await sendAjax('https://api.apiopen.top/api/getHaoKanVideo', {page: 2, size: 5})
            console.log('第3次请求成功了', res3)
        } catch (e) {
            console.log(e)
        }
    })()
</script>
</body>
</html>
